package whf.framework.security.service;

import java.util.List;
import java.util.Set;

import whf.framework.exception.FindException;
import whf.framework.exception.ServiceNotFoundException;
import whf.framework.security.dao.PermissionDAO;
import whf.framework.security.entity.Permission;
import whf.framework.security.entity.Role;
import whf.framework.util.BeanFactory;
import whf.framework.util.Utils;

/**
 * @author wanghaifeng
 * @email king@126.com
 * @modify 2006-05-31
 */
public class PermissionServiceImp extends whf.framework.service.ServiceImp<Permission> implements PermissionService {

	/**
	 * @property PermissionDAO:permissionDAO
	 */
	private PermissionDAO permissionDAO;

	/**
	 * @modify wanghaifeng Aug 28, 2006 11:03:54 PM
	 * @param permissionDAO
	 */
	public void setPermissionDAO(PermissionDAO permissionDAO) {
		this.permissionDAO = permissionDAO;
	}

	/**
	 * @modify wanghaifeng Aug 28, 2006 11:03:54 PM
	 * @return
	 * @throws ServiceNotFoundException
	 */
	public static PermissionService getPermissionService() throws ServiceNotFoundException {
		return (PermissionService)BeanFactory.getService(PermissionServiceImp.class) ;
	}

	/* (non-Javadoc)
	 * @see whf.framework.auth.service.PermissionService#findByTargetOperation(java.lang.String, java.lang.String)
	 */
	public Permission findByTargetOperation(String target, String operation) throws FindException {
		String sql = "t.target=? and (t.operation=? or t.prepareOperation=? or t.serviceOperation=? )";
		List<Permission> list = this.permissionDAO.find(sql, new Object[]{target, operation, operation, operation});
		if(list.size() > 0){
			return list.get(0);
		} else {
			return null;
		}
	}

	/* (non-Javadoc)
	 * @see whf.framework.auth.service.PermissionService#findByTarget(java.lang.String)
	 */
	public List<Permission> findByTarget(String target) throws FindException {
		return super.find("t.target=?", target);
	}

	/* (non-Javadoc)
	 * @see whf.framework.auth.service.PermissionService#findByRole(whf.framework.auth.entity.Role)
	 */
	public Set<Permission> findByRole(Role role) throws FindException {
		Set<Permission> perms = Utils.newHashSet();
		List<Permission> list = this.permissionDAO.findBySql("where permission_id in(select permission_id from framework_role_permission where role_id="+role.getId()+")", 0 , Integer.MAX_VALUE);
		perms.addAll(list);
		return perms;
	}

	
} 